package com.qf.realm;

import com.google.inject.CreationException;
import com.qf.pojo.SysUsers;
import com.qf.service.MenuService;
import com.qf.service.RoleService;
import com.qf.service.UserSerice;
import org.apache.ibatis.annotations.Param;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Set;

/*
 *@Description:
 *@author:刘哥
 *@Date:16:04 2022/7/19
 */
//认证
public class MyUserRealm extends AuthorizingRealm {
    @Autowired
    UserSerice userSerice;
    @Autowired
    RoleService roleService;
    @Autowired
    MenuService menuService;
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
//        System.out.println("222222");
//        获取认证查询的用户
        SysUsers user = (SysUsers) principalCollection.getPrimaryPrincipal();
        System.out.println(user.getId());
//        根据id查找用户的角色
        Set<String> roles=roleService.findRoles(user.getId());
//        根据id查找用户的权限
        Set<String> perms=menuService.findPerms(user.getId());
//        处理授权信息
//        AuthorizationInfo authorizationInfo=new SimpleAuthorizationInfo();
        SimpleAuthorizationInfo authorizationInfo=new SimpleAuthorizationInfo();
//        存储角色
        authorizationInfo.setRoles(roles);
//        存储权限
        authorizationInfo.setStringPermissions(perms);
        return authorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
//        System.out.println("1111");
   //在token里面对象中用户名是String类型可以直接强转
        String username = (String) authenticationToken.getPrincipal();
        //        token里面password是char数组，需要强转
        String password = new String((char[]) authenticationToken.getCredentials());

        System.out.println("前端获取到的用户名是"+username+"密码"+password);

//        调用业务逻辑,根据用户名查询用户,获取用户信息
        SysUsers user =userSerice.findByUsername(username);
        System.out.println("数据库的用户名"+user.getUsername()+"数据库的密码"+user.getPassword());
        if (user == null) {
            throw new UnknownAccountException("未知用户名");
        }
        if (user.getStatus()== 0) {
            throw new LockedAccountException("账户已锁定");
        }
        if(!password.equals(user.getPassword())){
            throw new CredentialsException("密码错误");        }

//        存储用户session (user,password,realmName)
        AuthenticationInfo authenticationInfo=new SimpleAuthenticationInfo(user,password,this.getName());
        return authenticationInfo;
    }
}
